package org.example.controller;

import org.example.domain.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/get-all-user")
    public String getAllUsers(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        System.out.println("/get-all-user" + users.size());
        return "user";
    }

    @RequestMapping("/del")
    public String test(@RequestParam("id") String userId, Model model) {

        try {
            userService.deleteById(userId);
        } catch (Exception e) {
            model.addAttribute("errMsg", e.toString());

            return "errorPage";
        }

        return "forward:/user/get-all-user";
    }

    @RequestMapping("/add")
    public String test(User user, Model model) {
        System.out.println(user);
        try {
            userService.addUser(user);
        } catch (Exception e) {
            model.addAttribute("errMsg", e.toString());
            return "errorPage";
        }
        return "redirect:/user/get-all-user";
    }
}
